/**
 * author: rayryuan
 * version: 1
 * date:2016-07-23
 *
 */

package com.tencent.wuyanzu.websocket;

import java.util.HashSet;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.alibaba.fastjson.JSONObject;
import com.tencent.wuyanzu.model.Restaurant;

public class Group {
	private final int DURATION_PER_VOTE = 30*100;   //30 second
	
	private Lock lock = new ReentrantLock();
	private String gID;
	private Set<WebSocket> sockets = new HashSet<WebSocket>();
	private Restaurant currentRst = null;
	private AtomicInteger  against = new AtomicInteger(0);
	private AtomicInteger  total = new AtomicInteger(0);
	
	private Timer timer ;
	private int currentTick = 0;
	private boolean doAgree =false;
	
	public Group(String gID){
		this.gID = gID;
	}
	
	public void start(){
		
		currentRst = generateRst();
		timer = new Timer();
		timer.schedule(new TimerTask() {
			public void run() {
				if(!doAgree) 
					if((++currentTick)==DURATION_PER_VOTE) {
						doAgree=true;
						broadcast();
						this.cancel();
					}
			}
		},10,10);
		broadcast();
	}
	
	public boolean isEmpty(){
		return sockets.isEmpty();
	}
	
	public String getID(){
		return gID;
	}
	
	public Timer getTimer(){
		return timer;
	}
	
	public boolean doAgree(){
		return doAgree;
	}
	
	public void addSocket(WebSocket ws){
		lock.lock();
		sockets.add(ws);
		total.incrementAndGet();
		lock.unlock();
		
	}
	
	public void removeSoeckt(WebSocket ws){
		lock.lock();
		sockets.remove(ws);
		total.decrementAndGet();
		//TODO pass
		lock.unlock();
	}
	
	public void oppose(String rid){
		lock.lock();
		if(!rid.equals(String.valueOf(currentRst.getRid()))){
			lock.unlock();
			return;
		}
		against.incrementAndGet();
		if(needPass()) pass();
		//TODO pass
		lock.unlock();
		
	}
	
	public boolean needPass(){
		return against.get()*2>total.get()?true:false;
	}
	
	public void pass(){
		against = new AtomicInteger(0);
		currentRst = generateRst();
		currentTick = 0;
	}
	

	/**
	 * 
	 * @return 推荐的餐馆
	 */
	
	private Restaurant generateRst() {
		// TODO
		return new Restaurant(0, "test:"+Math.random(), "test", "test", 0, 0);
	}


	public void broadcast() {
		JSONObject ret = new JSONObject();
		ret.put("groupID", gID);
		ret.put("currentSec",currentTick/100);
		ret.put("Total", total.get());
		ret.put("Against", against);
		ret.put("doAgree", doAgree);
		ret.put("restaurant", currentRst);
		
		for(WebSocket each : sockets){
			each.send(ret.toJSONString());
		}
		
	}
	
	
}
